<template>
  <a-modal v-model:open="ShowModalFlag" title="选择商品" @cancel="hideModal" @ok="hideModal" width="60vw" :bodyStyle="{ height: '520px' }">
    <template #default>
      <a-row :gutter="10">
        <a-col :span="4" style="margin-top: 10px">
          <CategoryTree ref="categoryTreeRef" v-model:value="company_cate_id" @update:value="() => queryData()" />
        </a-col>

        <a-col :span="20" style="background-color: #f8f8f8; padding: 20px; border-radius: 8px">
          <!---------- 查询表单form begin ----------->
          <a-form class="smart-query-form" :model="queryForm">
            <a-form-item label="商品名称" class="smart-margin-bottom0">
              <a-input v-model:value.trim="goods_name" placeholder="商品名称、助记码" autofocus allow-clear />
            </a-form-item>
            <a-form-item label="商品编码" class="smart-margin-bottom0">
              <a-input v-model:value.trim="no" placeholder="商品编码" allow-clear />
            </a-form-item>
            <a-button-group>
              <a-button type="primary" html-type="submit" @click="onSearch">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button @click="resetQueryData">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
            </a-button-group>
          </a-form>

          <!---------- 查询表单form end ----------->
          <a-table size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'auto', y: 320 }" :pagination="false" :showSorterTooltip="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, preserveSelectedRowKeys: true }">
            <template #bodyCell="{ text, record, column }">
              <template v-if="column.dataIndex === 'img'">
                <a-image :width="text ? 30 : 50" :src="text || failImg" />
              </template>
              <template v-if="column.dataIndex === 'un_fulfilled_num'">
                {{ Number(record.num) - Number(record.fulfilled_num) }}
              </template>
              <template v-if="column.dataIndex === 'stock'">
                <span v-if="props.warehouseType === 2">
                  {{ getSpecQuantity(record.totalQuantities, record.spec) }}
                  {{ record?.spec?.unit_name }}
                </span>
                <span v-if="props.warehouseType === 1">
                  {{ getSpecQuantity(record.totalPredQuantities, record.spec) }}
                  {{ record?.spec?.unit_name }}
                </span>
              </template>
            </template>
          </a-table>
          <div class="smart-query-table-page">
            <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
          </div>
        </a-col>
      </a-row>
    </template>
    <template #footer>
      <a-button type="primary" @click="onSubmit" html-type="button" style="margin-top: 10px">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { searchApi } from '@/api/search/search-api'
import CategoryTree from '@/components/business/category-tree/index.vue'
import failImg from '@/assets/images/notice/failImg.png'
const { getSpecQuantity } = useTransformSpec()
const emit = defineEmits(['confirm'])
const props = defineProps({
  checkStock: {
    type: Boolean,
    default: false // 是否检查库存
  },
  orderType: {
    type: Number,
    default: 1 // 1: 销售单 2: 退货单 3: 订货单
  },
  bookType: {
    type: Number,
    default: 1 // 订货类型 1: 订货单 2: 订退单
  },
  warehouseType: {
    type: Number,
    default: 1 // 1: 固定 2: 移动
  },
  defaultSelectedKeys: {
    type: Array<number>,
    default: () => []
  }
})
// ---------------------------- 表格列 ----------------------------
const columns = computed(() => [
  {
    title: '图片',
    dataIndex: 'img'
  },
  {
    title: '商品名称',
    dataIndex: ['goods', 'goods_name']
  },
  {
    title: '库存',
    dataIndex: 'stock'
  },
  {
    title: '订货数',
    dataIndex: 'num'
  },
  {
    title: '已履约',
    dataIndex: 'fulfilled_num'
  },
  {
    title: '未履约',
    dataIndex: 'un_fulfilled_num'
  },
  {
    title: '单位',
    dataIndex: ['spec', 'unit_name']
  },
  {
    title: '规格',
    dataIndex: ['spec', 'spec_name'],
    width: 100
  },
  {
    title: '单价',
    dataIndex: 'real_price'
  },
  {
    title: '规格条码',
    dataIndex: ['spec', 'barcode']
  },
  {
    title: '商品编码',
    dataIndex: ['goods', 'no']
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const company_cate_id = ref(0)
const store_id = ref(0)
const dealer_id = ref(0)
const goods_name = ref('')
const no = ref('')
const { queryForm, tableData, tableLoading, total, onSearch, resetQuery, queryData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const result = {
      list: [],
      total: 0
    }
    if (props.orderType === 3) {
      const data = {
        ...params,
        cate_id: company_cate_id.value,
        warehouse_id: warehouse_id.value,
        type: props.bookType,
        store_id: store_id.value,
        dealer_id: dealer_id.value,
        goods_name: goods_name.value,
        no: no.value
      }
      const res = await searchApi.bookOrderGoodsList(data)
      result.list = res.data.data
      result.total = res.data.total
    }
    return result
  },
  queryFormFilter: {},
  queryFormOp: {}
})

// ---------------------------- 规格 ----------------------------

// 选择表格行
const selectedRowKeyList = ref<number[]>([])
const selectedRowList = ref<any[]>([])

function onSelectChange(selectedRowKeys: number[], selectedRows: any[]) {
  selectedRowKeyList.value = selectedRowKeys
  selectedRowList.value = selectedRows
}

const ShowModalFlag = ref(false)
function hideModal() {
  ShowModalFlag.value = false
  resetQuery()
  selectedRowList.value = []
  selectedRowKeyList.value = []
}
function resetQueryData() {
  goods_name.value = ''
  no.value = ''
  resetQuery()
}
const warehouse_id = ref<number>()
const location_id = ref()

function showModal(params: { warehouse_id: number; dealer_id: number; location_id: number; store_id: number }) {
  warehouse_id.value = params.warehouse_id
  location_id.value = params.location_id || ''
  ;(store_id.value = params.store_id), (dealer_id.value = params.dealer_id)
  setQuery({}, true)
  queryData()
  ShowModalFlag.value = true
}

function onSubmit() {
  try {
    if (props.checkStock) {
      selectedRowList.value.forEach((item) => {
        const stock = props.warehouseType === 2 ? item.totalQuantities : item.totalPredQuantities
        if (Number(getSpecQuantity(stock, item.spec)) === 0) {
          throw new Error(`${item?.goods?.goods_name}库存不足！`)
        }
      })
    }
    if (selectedRowList.value.length > 0) {
      emit('confirm', selectedRowList.value)
      hideModal()
    }
  } catch (error) {
    message.error(error.message)
  }
}

defineExpose({
  showModal,
  hideModal
})
</script>

<style lang="less" scoped>
.smart-query-form {
  --grid-column-col: 4;
  padding-left: 0;
  padding-right: 0;
  background-color: #f8f8f8;
}
</style>
